package me.android.library.common.service.monitor;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

/**
 * 连接监控前台服务类
 * 负责将连接监控实现包装为前台服务
 */
public class ConnectionMonitorService extends Service {
    private static final String TAG = "ConnMonitorService";

    // Binder实例
    private final LocalBinder binder = new LocalBinder();

    // 连接监控实现
    private ConnectionMonitorServiceImpl connectionMonitor;

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化连接监控实现
        connectionMonitor = new ConnectionMonitorServiceImpl(this);

        // 启动监控
        connectionMonitor.startMonitoring();

        // 启动前台服务
        startForeground(ConnectionMonitorServiceImpl.NOTIFICATION_ID, createNotification());
    }

    /**
     * 创建前台服务通知
     */
    private Notification createNotification() {
        return connectionMonitor.createNotification();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 停止监控
        if (connectionMonitor != null) {
            connectionMonitor.stopMonitoring();
        }
    }

    /**
     * 获取蓝牙连接监控接口
     */
    public BluetoothConnectionMonitor getBluetoothMonitor() {
        return connectionMonitor;
    }

    /**
     * 获取WiFi P2P连接监控接口
     */
    public WifiP2pConnectionMonitor getWifiP2pMonitor() {
        return connectionMonitor;
    }

    /**
     * 本地Binder类
     */
    public class LocalBinder extends Binder {
        public ConnectionMonitorService getService() {
            return ConnectionMonitorService.this;
        }
    }
}

